package workerwithdb.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import workerwithdb.managers.SortMastersBy;
import autoservice.api.entitites.IMaster;
import autoservice.api.entitites.IOrder;
import entities.Master;

public class HibernateDAOMaster extends GenericDAOHibernate<IMaster> {
	private final String MASTER = "master";
	private final String NAME = "name";
	private final String NUMBER = "number";
	private final String DEADLINE_DATE = "deadlinedate";
	private final String ORDER_STATUS = "orderstatus";
	private final String EMPLOYMENT = "employment";

	public HibernateDAOMaster() {
		super(IMaster.class);
	}

	public void insertAllMasters(ArrayList<IMaster> mastersList, Session session)
			throws HibernateException {
		for (IMaster m : mastersList) {
			super.saveOrUpdate(m, session);
		}

	}

	public List<IMaster> sortMasters(SortMastersBy sort, Session session)
			throws HibernateException {
		Criteria criteria = session.createCriteria(Master.class).addOrder(
				Order.asc(sort.toString().toLowerCase()));
		@SuppressWarnings("unchecked")
		List<IMaster> sortMastersList = criteria.list();
		return sortMastersList;
	}

	public IOrder getOrderByMaster(String masterName, Session session)
			throws HibernateException {
		Criteria criteria = session.createCriteria(Order.class)
				.setFetchMode(MASTER, FetchMode.JOIN).createCriteria(MASTER)
				.add(Restrictions.eq(NAME, masterName));
		IOrder order = (IOrder) criteria.uniqueResult();
		return order;
	}

	public IMaster readMaster(String masterName, Session session)
			throws HibernateException {
		return (IMaster) super.get(NAME, masterName, session);
	}

	public Long getEmptyMastersOnDate(Date date, Session session)
			throws HibernateException {
		Criteria criteriaMasters = session.createCriteria(Master.class)
				.setProjection(Projections.count(NAME))
				.add(Restrictions.eq(EMPLOYMENT, false));
		Long countMasters = (Long) criteriaMasters.uniqueResult();
		Criteria criteriaOrders = session.createCriteria(IOrder.class)
				.setProjection(Projections.count(NUMBER))
				.add(Restrictions.lt(DEADLINE_DATE, date))
				.add(Restrictions.isNull(ORDER_STATUS));
		Long countOrders = (Long) criteriaOrders.uniqueResult();
		Long countMaster = countMasters + countOrders;
		return countMaster;

	}

}
